package com.example.moveclock.activities;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;

public class MainActivity extends Activity {
	
	private static double SPEED_MULTIPLIER = 1; 
	private static double SPEED_ACCELERATION = 0.05; 
	private static double SPEED_SLOWDOWN = 0.0125;
	private static double MAX_SPEED = 4;
	
	private TimeHandler mHandler;
	
	private double upSpeed = 0;
	private double downSpeed = 0;
	private double leftSpeed = 0;
	private double rightSpeed = 0;
	
	private boolean moveUp = false;
	private boolean moveDown = false;
	private boolean moveLeft = false;
	private boolean moveRight = false;
	
	private double xPosition;
	private double yPosition;
	private Timer timer = new Timer();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setupButtonListeners();
		mHandler = new TimeHandler();
		mHandler.setClock((AnalogClock) findViewById(R.id.analogClock1));
		this.startTimer();
		//RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.rLayout);
		//rLayout.addView(new SampleView(this));
		
		
	}

    /*
    private static Bitmap makeBitmap2() {
        Bitmap bm = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bm);
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setColor(Color.GREEN);
        p.setAlpha(0xCC);
        c.drawCircle(32, 32, 27, p);
        return bm;
    }
    
    private static class SampleView extends View {
        private final Shader mShader2;
        private final Paint mPaint;
        private final DrawFilter mFastDF;
        
        private float mTouchStartX;
        private float mTouchStartY;
        private float mTouchCurrX;
        private float mTouchCurrY;
        private DrawFilter mDF;

        public SampleView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);

            mFastDF = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG |
                                               Paint.DITHER_FLAG,
                                               0);

            mShader2 = new BitmapShader(makeBitmap2(), Shader.TileMode.REPEAT,
                                        Shader.TileMode.REPEAT);
            
            Matrix m = new Matrix();
            m.setRotate(30);
            mShader2.setLocalMatrix(m);
            
            mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
        }
        
        @Override protected void onDraw(Canvas canvas) {
            canvas.setDrawFilter(mDF);

            //mPaint.setShader(mShader1);
            //canvas.drawPaint(mPaint);
            
            canvas.translate(mTouchCurrX - mTouchStartX,
                             mTouchCurrY - mTouchStartY);

            mPaint.setShader(mShader2);
            canvas.drawPaint(mPaint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();
            
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mTouchStartX = mTouchCurrX = x;
                    mTouchStartY = mTouchCurrY = y;
                    mDF = mFastDF;
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mTouchCurrX = x;
                    mTouchCurrY = y;
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    mDF = null;
                    invalidate();
                    break;
            }
            return true;
        }
    }*/
	
	private class TimeHandler extends Handler {
			private AnalogClock clock;
			
			public void handleMessage(Message msg) {
				upSpeed = calculateSpeed(moveUp, upSpeed);
				downSpeed = calculateSpeed(moveDown, downSpeed);
				leftSpeed = calculateSpeed(moveLeft, leftSpeed);
				rightSpeed = calculateSpeed(moveRight, rightSpeed);
				calculatePositionXY();
				stopIfObjectReachBorder();
			
				
				clock.layout((int)xPosition, 
						(int)yPosition,
						(int)xPosition + clock.getWidth(), 
						(int)yPosition + clock.getHeight());
			}
			
		private void stopIfObjectReachBorder() {
			if(xPosition < findViewById(R.id.topLayout).getLeft()){
				xPosition = findViewById(R.id.topLayout).getLeft();
				if(leftSpeed - rightSpeed > 0.8 * SPEED_MULTIPLIER){
					rightSpeed = leftSpeed * 0.5;
				}
				leftSpeed = 0;
			}
				if(yPosition < findViewById(R.id.topLayout).getTop()){
					yPosition = findViewById(R.id.topLayout).getTop();
					if(upSpeed - downSpeed > 0.8 * SPEED_MULTIPLIER){
						downSpeed = upSpeed * 0.5;
					}
					upSpeed = 0;
				}
				if(xPosition + clock.getWidth() > findViewById(R.id.topLayout).getRight()){
					xPosition = findViewById(R.id.topLayout).getRight() - clock.getWidth();
					if(rightSpeed - leftSpeed > 0.8 * SPEED_MULTIPLIER){
						leftSpeed = rightSpeed * 0.5;
					}
					rightSpeed = 0;
				}
				if(yPosition + clock.getHeight() > findViewById(R.id.topLayout).getBottom()){
					yPosition = findViewById(R.id.topLayout).getBottom() - clock.getHeight();
					if(downSpeed - upSpeed > 0.8 * SPEED_MULTIPLIER){
						upSpeed = downSpeed * 0.5;
					}
					downSpeed = 0;
				}
			}
		
		

		private void calculatePositionXY() {
			if (yPosition == 0) {
				yPosition = clock.getTop();
			}
			//yPosition = calculatePositionForCurrentSpeedWithSlowdown();
			yPosition = yPosition + 
					(downSpeed - upSpeed);
			
			if (xPosition == 0) {
				xPosition = clock.getLeft();
			}
			xPosition = xPosition + 
					(rightSpeed - leftSpeed);
		}

			private double calculateSpeed(boolean shouldMove, double currentSpeed) {
				double calculatedSpeed = currentSpeed;
				if(shouldMove && currentSpeed < MAX_SPEED * SPEED_MULTIPLIER){
					calculatedSpeed = currentSpeed + SPEED_ACCELERATION * SPEED_MULTIPLIER;
				}
				else if(!shouldMove){
					//add slowdown to another variable
					calculatedSpeed = currentSpeed - SPEED_SLOWDOWN * SPEED_MULTIPLIER;
				}
				if(calculatedSpeed < 0){
					calculatedSpeed = 0;
				}
				return calculatedSpeed;
			}

			void setClock(AnalogClock clockToSet){
				clock = clockToSet;
			}
		};
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	protected void startTimer() {
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                mHandler.sendMessage(new Message());

            }
        }, 0, 10);
    }
	
	public void exit(View view) {
		Log.d("exit", "perform exit");
		MainActivity.this.finish();
	}
	
	private void setupButtonListeners() {
		Button upButton = (Button)findViewById(R.id.upButton);
		Button downButton = (Button)findViewById(R.id.downButton);
		Button leftButton = (Button)findViewById(R.id.leftButton);
		Button rightButton = (Button)findViewById(R.id.rightButton);
		upButton.setOnTouchListener(new CustomTouchListener(1));
		downButton.setOnTouchListener(new CustomTouchListener(2));
		leftButton.setOnTouchListener(new CustomTouchListener(3));
		rightButton.setOnTouchListener(new CustomTouchListener(4));
	}
	
	public class CustomTouchListener implements View.OnTouchListener { 
		int buttonDirection;
		
		public CustomTouchListener(int buttonDirection){
			this.buttonDirection = buttonDirection;
		}
		public boolean onTouch(View v, MotionEvent event) {
			switch(event.getAction()){            
            case MotionEvent.ACTION_DOWN:
				switch (buttonDirection) {
				case 1:
					moveUp = true;
					break;
				case 2:
					moveDown = true;
					break;
				case 3:
					moveLeft = true;
					break;
				case 4:
					moveRight = true;
					break;
				}
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
            	moveUp = false;
            	moveDown = false;
            	moveLeft = false;
            	moveRight = false;
                break;
			} 
        return false;   
		} 
		
		
	}
	
	@Override
	protected void onDestroy() {
		timer.cancel();
		super.onDestroy();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_item_exit:
	        	this.finish();
	            return true;
	        case R.id.menu_settings:
	            //showHelp();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	
	/*
	
	
	//static final String STARTS_COUNT = "startsCount";
	//int startsCount = 0;
	int count = 0;
	TextView textView1;
	boolean moveObject = false;
	int moveDown = 1;
	int moveCount = 200;
	private GameProcess process;

	

	private Runnable runnable = new Runnable() {
		//AnalogClock clock = (AnalogClock) findViewById(R.id.analogClock1);
		
	    public void run() {
			final AnalogClock clock = (AnalogClock) findViewById(R.id.analogClock1);
			clock.layout(clock.getLeft()+20, 
					clock.getTop(), 
					clock.getRight()+20, 
					clock.getBottom());
			clock.invalidate();
clock.refreshDrawableState();
				    		while(moveCount > 0){
				    			clock.layout(clock.getLeft(), 
				    					clock.getTop() + moveDown, 
				    					clock.getRight(), 
				    					clock.getBottom() + moveDown);
				    			clock.invalidate();
				    			clock.refreshDrawableState();
				    			moveCount = moveCount - 1;
				    			
				    		}

	     }
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setupButtonListeners();
		textView1 = (TextView)findViewById(R.id.textView1);
		//process = new GameProcess();
		//process.start();
		this.startTimer();
		//mHandler.postDelayed(runnable, 2000);


		
	}
	



	private void setupButtonListeners() {
		Button button = (Button)findViewById(R.id.button1);
		button.setOnTouchListener(new CustomTouchListener());
	}
	
	public class CustomTouchListener implements View.OnTouchListener { 


		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch(event.getAction()){            
            case MotionEvent.ACTION_DOWN:
            	moveObject = true;
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
            	moveObject = false;
                break;
			} 
        return false;   
		} 
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	    // Save the user's current game state
	    //savedInstanceState.putInt(STARTS_COUNT, startsCount + 1);
	    super.onSaveInstanceState(savedInstanceState);
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	    // Always call the superclass so it can restore the view hierarchy
		
	    super.onRestoreInstanceState(savedInstanceState);
	    *//*
	    if (savedInstanceState != null) {
			startsCount = savedInstanceState.getInt(STARTS_COUNT);
	    }
		TextView textViewStartsCount = (TextView) findViewById(R.id.textViewStartsCount);
		textViewStartsCount.setText("Restarts: " + startsCount);
		
	    // Restore state members from saved instance
	    savedInstanceState.putInt(STARTS_COUNT, startsCount);
	    *//*
		
	}
	
	@Override
	public void onResume(){
		super.onResume();
		ImageView arrow = (ImageView) findViewById(R.id.imageArrow1);
		arrow.setVisibility(android.view.View.INVISIBLE);
		
		
	}

	private void moveArrow() {
		
		android.os.Debug.stopMethodTracing();

		ImageView arrow = (ImageView) findViewById(R.id.imageArrow1);
		
		AnimationSet aset = new AnimationSet(false);

		Animation rotation = new RotateAnimation(180, 220);
		rotation.setDuration(3000);
		rotation.setStartOffset(5000);
		
		Animation animation = new TranslateAnimation(getRelativeLeft(arrow),
				getRelativeLeft(arrow) + 100,
				getRelativeTop(arrow),
				getRelativeTop(arrow) + 100);
		animation.setDuration(5000);
		

		
		aset.addAnimation(rotation);
		aset.addAnimation(animation);
		
		arrow.startAnimation(aset);
	}
	
	private int getRelativeLeft(View myView) {
	    if (myView.getParent() == myView.getRootView())
	        return myView.getLeft();
	    else
	        return myView.getLeft() + getRelativeLeft((View)myView.getParent());
	}

	private int getRelativeTop(View myView) {
	    if (myView.getParent() == myView.getRootView())
	        return myView.getTop();
	    else
	        return myView.getTop() + getRelativeTop((View)myView.getParent());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_item_exit:
	        	this.finish();
	            return true;
	        case R.id.menu_settings:
	            //showHelp();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	public void up(View view) {
		moveVertival = -1;
	}

	public void down(View view) {
		moveVertival = 1;
	}
	
	public void left(View view) {
		
	}
	



	public void right(View view) {
		AnalogClock clock = (AnalogClock) findViewById(R.id.analogClock1);
		clock.layout(clock.getLeft() + 10, 
				clock.getTop(), 
				clock.getRight() + 10, 
				clock.getBottom());
		
	}
	
	public void exit(View view) {
		Log.d("exit", "perform exit");
		MainActivity.this.finish();
	}
	*/
}
